/*
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *
 *   版权所有  2014-2015 成都星锐蓝海网络科技有限公司
 *   商业许可请联系  +86-18682011860    QQ:66442834
 *   
 */

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <getopt.h>
#include <pthread.h>
#include <netinet/in.h>
#include "xyz_log.h"
#include "xyz_int.h"
#include "xyz_str.h"
#include "wmpctrl.h"
#include "wtpnl.h"
#include "wtpinfo.h"

#include "global.h"

static int S_log_level = XYZ_LOG_LEVEL_WARN;
static int S_debug_flag = 0;

int G_wmpsock = -1;

struct sockaddr_in G_wmpaddr;

static int S_state = WTP_STATE_INIT;    /* 当前AP的状态  */
int G_nlksock = -1;       /*  连接AC的套接字  */
int G_dscv_count = 0;    /* 发现计数器   */

const char *short_options = "hdv";
const struct option long_options[] = {
		{"version",	0,	NULL,	'v'},
		{"help",	0,	NULL,	'h'},
		{"debug",	0,	NULL,   'd'},
		{ NULL,	    0,	NULL,	 0}
};

extern void wmpInit(int *state);
extern void wmpDscv(int *state);
extern void wmpSulk(int *state);
extern void wmpJoin(int *state);
extern void nsap_firm_upgr(int *state);
extern void wmpRun(int *state);
extern void wmpWait(int *state);
extern void wmpRecov(int *state);

const char *nsap_deid_get_string(void);

int nsap_prep_env(void);
const nsap_firm_ver_t *nsap_firm_version(void);
void mainExit(void);
void exitSignalHandle(int sig);
void signalsInit(void);
static void usage(void);






int nsap_prep_env(void)
{
/* 初始化存放设备ID的硬件，本程序省略了读取硬件部分代码
	if (nsap_deid_init()) {
		xyz_log_error("NS-AP init Device-Id failed");
		return -1;
	}
 */
	xyz_log_debug("NS-AP Device-Id is \"%s\"", nsap_deid_get_string());
	if (!nsap_board_name()) {
		xyz_log_error("NS-AP init Board-Name failed");
		return -1;
	}
	xyz_log_debug("NS-AP Board-Name is \"%s\"", nsap_board_name());
/*  硬件相关，不需要初始化。
	if (nsap_firm_version_init()) {
		xyz_log_error("NS-AP init Firmware-Version failed");
		return -1;
	}
*/
	nsap_firm_ver_t *ver = (nsap_firm_ver_t *)nsap_firm_version();
	xyz_log_debug("NS-AP Firmware-Version is \"%d.%d.%d\"", ver->major, ver->minor, ver->patch);
	if (nsap_dscv_addr_init()) {
		xyz_log_error("NS-AP init Discovery-Address failed");
		return -1;
	}
/* 不需要初始化ORG和BRC，程序指定。
	if (nsap_orgbrc_init(NULL, NULL)) {
		xyz_log_error("NS-AP init ORG-BRC failed");
	}
*/
	xyz_log_debug("NS-AP Discovery-Address is \"%s\"", nsap_dscv_addr_get_addr());
	xyz_log_debug("NS-AP prep init done");
	return 0;
}

void mainExit(void)
{
    /*
	if (nsap_wifi_stop() != 0) {
		xyz_log_error("stop WiFi failed!");
	}
	if (wtpInfoSendHookClose2Krn()) {
		xyz_log_error("Stop HOOK error");
	}
      */
    xyz_log_error("Wifi is stop!");
	xyz_log_close();
	if (G_nlksock > 0) {
		close(G_nlksock);
	}
	if (G_wmpsock > 0) {
		close(G_nlksock);
	}
}


void exitSignalHandle(int sig)
{
	xyz_log_warn("signal %d, the progress exit", sig);
	mainExit();
	exit(1);
}

void signalsInit(void)
{
	signal(SIGINT, exitSignalHandle);
	signal(SIGKILL, exitSignalHandle);
}

/*
 * usage
 */
static void usage(void)
{
	printf("Usage:\n-h	--help \n");
	printf("-d	--debug \n");
	exit(-1);
}



static void parseArgs(int argc, char **argv)
{
	int rc = 0;
	while((rc = getopt_long(argc, argv, short_options, long_options, NULL)) != -1) {
		switch(rc){
		case 'v':
			printf("1.0.8\n");
			exit(0);
			break;
		case 'h':
			usage();
			break;
		case 'd':
			S_log_level = XYZ_LOG_LEVEL_DEBUG;
			S_debug_flag = 1;
			break;
		default :
			break;
		}
	}
}



int main(int argc, char **argv)
{
	parseArgs(argc, argv);

	if (0 == S_debug_flag) {
		xyz_log_init("/tmp/ap.log", XYZ_LOG_LEVEL_WARN, 65536);
		daemon(1, 1);
	} else {
		xyz_log_init("stdout", XYZ_LOG_LEVEL_DEBUG, 0);
	}
	if (nsap_prep_env()) {
		xyz_log_error("NS-AP init ENV failed");
		return -1;
	}
	signalsInit();
/* AP启动完毕后，改变AP LED的状态，显示AP启动个完毕了。
 * system("/sbin/ns_led.sh down &");
 * 系统启动完毕后，AP进程进入循环状态。
*/
	for ( ; ; ) {
		switch (S_state) {
			case WTP_STATE_INIT :
				xyz_log_debug("==========INIT STATE==========");
				G_dscv_count = 0;
				wmpInit(&S_state);break;
			case WTP_STATE_DSCV :
				xyz_log_debug("==========DSCV STATE==========");
				G_dscv_count++;
				wmpDscv(&S_state);break;
			case WTP_STATE_SULK :
				xyz_log_debug("==========SULK STATE==========");
				wmpSulk(&S_state);break;
			case WTP_STATE_JOIN :
				xyz_log_debug("==========JOIN STATE==========");
				wmpJoin(&S_state);break;
#if 0
			case WTP_STATE_IMAGE :
				xyz_log_debug("==========IMAGE STATE==========");
				nsap_firm_upgr(&S_state);break;
#endif
			case WTP_STATE_RUN :
				xyz_log_debug("==========RUN STATE==========");
				wmpRun(&S_state);break;
			case WTP_STATE_WAIT :
				xyz_log_debug("==========WAIT STATE==========");
				wmpWait(&S_state);break;
			case WTP_STATE_RECOV :
				xyz_log_debug("==========RECOV STATE==========");
				wmpRecov(&S_state);
				break;
			default :
				break;
		}
	}
	return 0;
}
